<template>
  <div>
    <el-upload
        ref="upload"
        list-type="picture-card"
        action
        :file-list="fileList"
        :show-file-list="true"
        :http-request="uploadFile"
        accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
        :limit="1"
        :on-remove="handleRemove"
        :on-change="handlePreview"
        :on-exceed="handleExceed"
        >
        <i class="el-icon-plus" />
    </el-upload>
  </div>
</template>

<script>
import { fileUpload } from "@/api/user";

export default {
	name: 'SingleUpload',
	props: {
		width: {
			type: String,
			required: true
		},
		height: {
			type: String,
			required: true
		},
		viewWidth: {
			type: String,
			required: true
		},
		viewHeight: {
			type: String,
			required: true
		},
		image: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			tmpUrl: this.image,
			img: this.image,
			loading: false,
			uploadError: false
		}
	},
	computed: {
		H() {
			const height = this.viewHeight
			const tHeight = height < 150 ? 150 : height
			return tHeight > 400 ? 400 : tHeight
		},
		W() {
			const width = this.viewWidth
			const tWidth = width < 150 ? 150 : width
			return tWidth > 750 ? 750 : tWidth
		},
		imageUrl: {
			get: function() {
				return (this.img && this.img.indexOf('http') === -1 && this.img.indexOf('//') === -1) ? config.staticUrl + this.img : this.img
			},
			set: function(newValue) {
				this.img = newValue
			}
		}
	},
	methods: {
		// 清除错误信息
		clearError() {
			this.uploadError = false
			this.$emit('focus', '')
		},

        async  beforeUpload(file) {
            const _this = this
            var formData = new FormData()
            formData.append('file', file.raw)
            const URLImg = await fileUpload(formData)
            _this.img_url = URLImg.data
            console.log(_this.img_url)
            console.log('-000---------------')
            // const _URL = window.URL || window.webkitURL
            const fileName = file.uid
            this.listObj[fileName] = {}
            return new Promise((resolve, reject) => {
                const img = new Image()
                img.src = _this.img_url
                img.onload = function() {
                _this.listObj[fileName] = { hasSuccess: false, url: _this.img_url, uid: file.uid, width: this.width, height: this.height }
                }
                resolve(true)
            })
        },
		// 上传
		async uploadHttp({ file }) {
			this.loading = true
			this.uploadError = false
			const fileName = (new Date()).toLocaleDateString() + '/' + randomFileName() + '.' + getFileType(file.name)
			this.$store.getters.uploadClient.put(`images/${fileName}`, file).then(({ res, url, name }) => {
				if (res && res.status === 200) {
					this.imageUrl = url
					this.$emit('change', name)
					this.tmpUrl = name // 方便在更改图片后将原来的图片在服务器删除
				}
			}).catch((err) => {
				this.uploadError = true
				console.log('上传图片失败', err)
			}).finally(() => {
				this.loading = false
			})
		},
		// 图片限制
		beforeUpload(file) {
			const allowedType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
			const isLt1500K = file.size / 1024 / 1024 <= 1.5
			if (!allowedType) {
				this.$message.error('上传图片只能是 JPEG/JPG/PNG/GIF 格式!')
			}
			if (!isLt1500K) {
				this.$message.error('单张图片大小不能超过 1.5M!')
			}
			return allowedType && isLt1500K
		},
		handleSuccess(file, fileList) {
			if (this.tmpUrl) {
				this.deleteServerFile(this.tmpUrl) // 删除成功后将原来的服务器文件删除
			}
		},
		// 服务器删除文件
		async deleteServerFile(url) {
			this.$store.getters.uploadClient.delete(url).then((res) => {
				console.log('实时删除服务器文件成功', res)
			}).catch((err) => {
				console.log('实时删除服务器文件失败', err)
			})
		}
	}
}
</script>

<style scoped lang="less">
.uploader {
    line-height: 0
}

.uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center
}

.text-tips {
    font-size: 10px;
    color: #409eff;
    background: #fffcd9;
    padding: 5px 8px;
    border-radius: 2px;
    line-height: 1.3;
    margin-top: 2px;
    text-align: center;
}

/deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden
}

/deep/ .el-upload:hover {
    border-color: #409eff
}
</style>